import { defineStore } from 'pinia'
import { login, getUserInfo, logout } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null
  }),
  
  getters: {
    userName: state => state.userInfo?.userName || '',
    userRole: state => state.userInfo?.userRole || ''
  },
  
  actions: {
    async login(userInfo) {
      try {
        const data = await login(userInfo)
        this.token = data.token
        localStorage.setItem('token', data.token)
        return data
      } catch (error) {
        throw error
      }
    },
    
    async getUserInfo() {
      try {
        const data = await getUserInfo()
        this.userInfo = data
        return data
      } catch (error) {
        throw error
      }
    },
    
    async logout() {
      try {
        await logout()
        this.token = ''
        this.userInfo = null
        localStorage.removeItem('token')
      } catch (error) {
        throw error
      }
    }
  }
}) 